﻿using System.Collections.Generic;
using System.Linq;
using ARMIR.util;
using RimWorld;
using Verse;

namespace ARMIR {
    /// <summary>
    /// 使战术装备03使用的建筑能够通过给予hediff周期性压制附近的敌人
    /// </summary>
    public class ThingComp_TMZeroThree : ThingComp {
        private CompPropertiesBuildingAbility_TMZeroThree Props => (CompPropertiesBuildingAbility_TMZeroThree)props;
        private int ticksUntilPulse;
        private int destroyTimes;
        private bool TotallyStop = false;
        //环渲染参数
        private bool isRinging; //是否处于渲染状态
        private float maxRing = 60; //环最大渲染到
        private float ringGrowthRate = 0.2f; //环增长速度
        private float indexRing = 0; //环增长状态

        public override void PostSpawnSetup(bool respawningAfterLoad) //生命周期管理
        {
            base.PostSpawnSetup(respawningAfterLoad);
            ticksUntilPulse = Props.intervalTicks;
            isRinging = false;
            destroyTimes = 0;
            TotallyStop = false;
        }

        public override void CompTick() //主循环
        {
            base.CompTick();
            if (!TotallyStop)
            {
                if (--ticksUntilPulse <= 0)
                {
                    Pulse();
                    destroyTimes++;
                    if (destroyTimes > 5)
                    {
                        destroySelf();
                    }
                    ticksUntilPulse = Props.intervalTicks;
                }
                drawBoxRing();
            }
        }

        public override void PostExposeData()
        {
            base.PostExposeData();
            Scribe_Values.Look(ref TotallyStop, "彻底停止", false);
        }

        private void Pulse() //主体
        {
            //检查同阵营的迷迭香是否存在
            List<Pawn> Rosmontis = new List<Pawn>();
            Rosmontis = parent.Map.mapPawns.AllHumanlikeSpawned.Where
            (p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_OriginiumBrainStem")) //是迷迭香
            && p.Faction == parent.Faction //同阵营
            && !p.Downed //未倒下
            && !p.Dead).ToList(); //未死亡
            if (Rosmontis.Count == 0) { 
                TotallyStop = true;
                destroySelf();
                return;
            }
            // 设置延迟
            TickUtil DelayTick = Current.Game.GetComponent<TickUtil>();
            //脉冲特效
            EffecterDef shockWave = DefDatabase<EffecterDef>.GetNamed("ARMIR_TMZeroThree_EffecterB"); //精神冲击波特效
            EffecterDef shockWaveB = DefDatabase<EffecterDef>.GetNamed("ARMIR_TMZeroThree_EffecterBB"); //精神冲击波特效
            shockWave.Spawn(parent.Position, parent.MapHeld);
            DelayTick.TickTimeManager(70, () => { 
                shockWaveB.Spawn(parent.Position, parent.MapHeld);
                isRinging = true;
            }, true);
            // 获取范围内所有生物
            foreach (Pawn pawn in GenRadial.RadialDistinctThingsAround(parent.Position, parent.Map, Props.radius, true)
                         .OfType<Pawn>()
                         .Where(p => p.Faction != parent.Faction && p.HostileTo(parent))) // 只影响不同阵营且敌对
            {
                ApplyDebuffs(pawn);
            }
        }

        private void ApplyDebuffs(Pawn pawn) {
            // 设置延迟
            TickUtil DelayTick = Current.Game.GetComponent<TickUtil>();
            DelayTick.TickTimeManager(70, () => {
                // 应用减速
                Hediff slow = HediffMaker.MakeHediff(Props.hediffSlow, pawn);
                pawn.health.AddHediff(slow);
                //受击特效
                EffecterDef hitFleck = DefDatabase<EffecterDef>.GetNamed("ARMIR_TMZeroThree_EffecterC"); //受击特效
                hitFleck.Spawn(pawn, pawn.MapHeld);
                //如果已被减速，则击晕
                if (pawn.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_mindRepression")))
                {
                    // 创建伤害信息
                    DamageInfo damageInfo = new DamageInfo(
                        DamageDefOf.Stun, // 使用击晕伤害类型
                        20,
                        armorPenetration: 0f,
                        instigator: null, // 可指定造成此伤害的对象
                        hitPart: null // 可指定击中的身体部位
                    );
                    // 对目标Pawn施加伤害
                    pawn.TakeDamage(damageInfo);
                }
            }, true);
        }

        public override void PostDrawExtraSelectionOverlays() {
            // 显示作用范围
            GenDraw.DrawRadiusRing(parent.Position, Props.radius);
        }
        private void drawBoxRing() {
            if (isRinging) {
                float baseHyaline = 1 - indexRing / maxRing;
                ARMIR_Draw.DrawBlocksWithCir(parent.Position.ToVector3(), indexRing, baseHyaline, 30, 4f, 1f);
                indexRing = indexRing + ringGrowthRate;
                if (indexRing > maxRing) {
                    isRinging = false;
                    indexRing = 0;
                }
            }
        }
        private void destroySelf() {
            speDraw.DragLight(parent.Map, parent.Position.ToVector3(), 10, 0.15f, 15, false, true, 0, 0.8f);
            parent.Destroy();
        }
    }
}